package org.example.demo.screen

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.VerticalDivider
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import cafe.adriel.voyager.core.model.rememberScreenModel
import cafe.adriel.voyager.core.screen.Screen
import coil3.compose.AsyncImage
import kmpproject.composeapp.generated.resources.Res
import kmpproject.composeapp.generated.resources.chat_msg_tip_default
import kmpproject.composeapp.generated.resources.paperplane_right_fill
import kmpproject.composeapp.generated.resources.xmark_circle
import org.example.demo.module.ChatModule
import org.jetbrains.compose.resources.painterResource
import org.jetbrains.compose.resources.stringResource

class ChatScreen(
    private val iconUrl: String,
    private val name: String,
    private val botId: String
) : Screen {

    @Composable
    override fun Content() {
        val chatModule = rememberScreenModel { ChatModule(botId) }
        Column(modifier = Modifier.fillMaxSize()) {
            val listState = rememberLazyListState()
            LaunchedEffect(chatModule.chatMsgList.size) {
                if (chatModule.chatMsgList.size - 1 >= listState.firstVisibleItemIndex) {
                    listState.animateScrollToItem(chatModule.chatMsgList.size - 1)
                }
            }
            LazyColumn(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(Color.Gray)
                    .weight(1f),
                state = listState
            ) {
                item {
                    Column(
                        modifier = Modifier.padding(16.dp).fillMaxWidth(),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        AsyncImage(
                            model = iconUrl,
                            contentDescription = null,
                            modifier = Modifier.size(80.dp)
                        )
                        Text(
                            text = name,
                            modifier = Modifier.padding(top = 16.dp)
                        )
                    }
                }
                items(chatModule.chatMsgList) {
                    Row(
                        modifier = Modifier.fillMaxWidth().padding(
                            start = if (it.isSelf) 80.dp else 8.dp,
                            end = if (it.isSelf) 8.dp else 80.dp,
                            top = 8.dp,
                            bottom = 8.dp
                        ),
                        horizontalArrangement = if (it.isSelf) Arrangement.End else Arrangement.Start,
                    ) {
                        if (!it.isSelf && !it.followUp) {
                            AsyncImage(
                                model = iconUrl,
                                contentDescription = null,
                                modifier = Modifier.padding(horizontal = 8.dp)
                                    .size(40.dp)
                                    .clip(CircleShape)
                            )
                        } else {
                            Spacer(modifier = Modifier.padding(horizontal = 8.dp).size(40.dp))
                        }
                        Column {
                            if (!it.isSelf && !it.followUp) {
                                Text(text = name)
                            }
                            Text(
                                text = it.content,
                                modifier = Modifier
                                    .then(
                                        if (it.followUp) {
                                            Modifier.clickable {
                                                chatModule.onSendClick(it.content)
                                            }.background(
                                                color = Color.White,
                                                shape = RoundedCornerShape(8.dp)
                                            )
                                                .border(
                                                    width = 1.dp,
                                                    color = Color.Blue,
                                                    shape = RoundedCornerShape(8.dp)
                                                )
                                        } else {
                                            Modifier.background(
                                                color = Color.White,
                                                shape = RoundedCornerShape(8.dp)
                                            )
                                        }
                                    ).padding(8.dp)
                            )
                            if (!it.isSelf && !it.followUp && it.reflectTime > 0) {
                                Text(
                                    text = "${it.reflectTime}s",
                                    modifier = Modifier.padding(top = 8.dp)
                                )
                            }
                        }
                    }
                }
            }

            EditorBar(
                modifier = Modifier.fillMaxWidth().height(50.dp),
                editorText = chatModule.editorText,
                onTextChanged = chatModule::onTextChanged,
                onSendClick = chatModule::onSendClick
            )
        }
    }
}

@Composable
private fun EditorBar(
    modifier: Modifier,
    editorText: State<String>,
    onTextChanged: (String) -> Unit,
    onSendClick: (String) -> Unit
) {
    BasicTextField(
        value = editorText.value,
        onValueChange = onTextChanged,
        singleLine = true,
        textStyle = TextStyle(fontSize = MaterialTheme.typography.bodyLarge.fontSize),
        modifier = modifier
            .padding(horizontal = 16.dp),
        cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),
        decorationBox = { innerTextField ->
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Spacer(modifier = Modifier.width(8.dp))

                Box(
                    modifier = Modifier
                        .weight(1f)
                ) {
                    if (editorText.value.isEmpty())
                        Text(
                            text = stringResource(Res.string.chat_msg_tip_default),
                            color = Color.Gray,
                            fontSize = MaterialTheme.typography.bodyLarge.fontSize
                        )

                    innerTextField()
                }

                // 存在焦点，且有输入内容时，显示叉号
                if (editorText.value.isNotEmpty()) {
                    Image(
                        painter = painterResource(Res.drawable.xmark_circle),
                        contentDescription = null,
                        modifier = Modifier
                            .size(24.dp)
                            .clickable { onTextChanged("") })
                }

                VerticalDivider(modifier = Modifier.padding(vertical = 16.dp, horizontal = 8.dp))

                Image(
                    painter = painterResource(Res.drawable.paperplane_right_fill),
                    contentDescription = null,
                    modifier = Modifier
                        .size(32.dp)
                        .clickable { onSendClick(editorText.value) })
            }
        }
    )
}